package com.zl.order.service.impl;

import com.zl.basic.service.impl.BaseServiceImpl;
import com.zl.basic.util.LoginContext;
import com.zl.basic.util.PageList;
import com.zl.order.domain.OrderPetAcquisition;
import com.zl.order.dto.OrderDto;
import com.zl.order.mapper.OrderPetAcquisitionMapper;
import com.zl.order.query.OrderPetAcquisitionQuery;
import com.zl.order.service.IOrderPetAcquisitionService;
import com.zl.org.domain.Employee;
import com.zl.org.domain.Shop;
import com.zl.org.mapper.EmpMapper;
import com.zl.org.mapper.ShopMapper;
import com.zl.pet.domain.SearchMasterMsg;
import com.zl.pet.mapper.PetMapper;
import com.zl.pet.mapper.SearchMasterMsgMapper;
import com.zl.user.domain.LoginInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;

/**
 * 业务实现类：
 */
@Service
public class OrderPetAcquisitionServiceImpl extends BaseServiceImpl<OrderPetAcquisition> implements IOrderPetAcquisitionService {
    @Autowired
    private EmpMapper empMapper;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;

    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private PetMapper petMapper;

    @Override
    public PageList<OrderPetAcquisition> queryPage(OrderPetAcquisitionQuery query, HttpServletRequest request) {
        LoginInfo loginUser = LoginContext.getLoginUser(request);
        Employee employee = empMapper.loadByLogininfoId(loginUser.getId());
        if (employee.getShop_id()!=null){
            Shop shop = shopMapper.loadById(employee.getShop_id());
            if (shop.getAdmin_id()!=employee.getId()){
                query.setEmpId(employee.getId());
            }
            query.setShopId(shop.getId());
        }
        return super.queryPage(query);
    }

    @Override
    public void confirm(OrderDto orderDto) {

        Long orderId = orderDto.getId();
        BigDecimal money = orderDto.getMoney();
        Integer paytype = orderDto.getPaytype();

        // 1.修改订单：state=1 money paytype
        OrderPetAcquisition order = orderPetAcquisitionMapper.loadById(orderId);
        order.setState(1);
        order.setPrice(money);
        order.setPaytype(paytype);
        orderPetAcquisitionMapper.update(order);
        //2。修改寻主信息：state=2 note
        SearchMasterMsg msg = searchMasterMsgMapper.loadById(order.getSearchMasterMsgId());
        msg.setState(2);
        msg.setNote("处理完成，交易成功");
        searchMasterMsgMapper.update(msg);



    }

    @Override
    public void remove(Long id) {
        OrderPetAcquisition order = orderPetAcquisitionMapper.loadById(id);
        // 将寻主消息中的shop_id置空 -返回到寻主池
        searchMasterMsgMapper.reject(order.getSearchMasterMsgId());
        //删除宠物-没有成功收购
        petMapper.remove(order.getPetId());
        //删除订单
        super.remove(id);
    }
}
